<template>
  <div>
    <div class="details">个性化精准学AI课程表</div>
    <div class="details-text">
      根据智慧诊断AI分析结果，所呈现的被测学生的薄弱点、失分点、对症下药，制定如下课程学习方案：
    </div>
    <div
      class="table-listname"
      v-for="(items, index) in details1.monopolize"
      :key="index"
    >
      <div class="tablesname">{{ items.MethodName }}</div>
      <div>
        <table
          class="course-table"
          :style="{ 'border-collapse': 'collapse', width: '100%' }"
        >
          <thead>
            <tr>
              <th>课程id</th>
              <th class="course-name">课程名称</th>
              <th>课程类型</th>
              <th>所属知识点</th>
              <th>时长</th>
              <th>所属班型</th>
              <th>学段学科</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in items.videoInfo" :key="item.id">
              <td class="nowrap">{{ item.VID }}</td>
              <td class="course-name">
                <!-- {{ item.VideoName }} -->

                <span v-html="item.VideoName"></span>
                <span style="margin-left: 1vw" @click="videolistao(item.VID)">
                  <img
                    style="width: 20px; height: 15px"
                    src="/img/shipin.png"
                    alt=""
                  />
                </span>
              </td>
              <td class="nowrap">{{ item.CourseTypeName }}</td>
              <td class="truncate">{{ item.KlName }}</td>
              <td class="nowrap">{{ item.VideoTime }}</td>
              <td class="truncate">{{ item.ClassName }}</td>
              <td class="nowrap">{{ item.grade }}</td>
            </tr>
          </tbody>
        </table>
        <!-- <a-table
        :pagination="false"
        :data="items.videoInfo"
       
        :bordered="false"
      >
        <template #columns>
          <a-table-column
            title="课程id"
            align="center"
            data-index="VID"
          ></a-table-column>
          <a-table-column
            title="课程名称"
            align="center"
            data-index="VideoName"
          >
            <template #cell="{ record }">
              <span v-html="record.VideoName"></span>
              <span class="imgliyu" @click="videolistao(record.VID)">
                <img  src="/img/shipin.png" alt="" />
              </span>
            </template>
          </a-table-column>
          <a-table-column
            title="课程类型"
            align="center"
            data-index="CourseTypeName"
          ></a-table-column>
          <a-table-column
            title="所属知识点"
            align="center"
            data-index="KlName"
          ></a-table-column>
          <a-table-column
            title="时长"
            align="center"
            data-index="VideoTime"
          ></a-table-column>
          <a-table-column
            title="所属班型"
            align="center"
            data-index="ClassName"
          ></a-table-column>
          <a-table-column
            title="学段学科"
            align="center"
            data-index="grade"
          ></a-table-column>
    
        </template>
      </a-table> -->
      </div>
    </div>
  </div>
  <a-modal
    v-model:visible="visible"
    @ok="handleOk"
    width="50vw"
    @cancel="handleCancel"
  >
    <template #title> {{ videoname }} </template>
    <div>
      <video
        ref="videoEl"
        controls
        :poster="poster"
        width="100%"
        class="videos-height"
      ></video>
    </div>
  </a-modal>
</template>
<script lang="ts" setup>
import { ref, reactive, onMounted, watch, onBeforeUnmount } from "vue";

import Hls from "hls.js";
import useUserStore from "@/store/modules/user";
import { catstudyCourse } from "@/api/study";
const videoEl = ref<HTMLVideoElement | null>(null);
const hlsInstance = ref<Hls | null>(null);
const poster = ref(""); // 视频封面URL
const videoUrl = ref(""); // M3U8视频URL
const VideoTime = ref();
// 初始化HLS播放器
const initHlsPlayer = async () => {
  if (!videoEl.value) return;
  // videoEl.value.addEventListener("timeupdate", handleTimeUpdate);
  try {
    if (Hls.isSupported()) {
      hlsInstance.value = new Hls();
      hlsInstance.value.loadSource(videoUrl.value);
      hlsInstance.value.attachMedia(videoEl.value);
      hlsInstance.value.on(Hls.Events.MANIFEST_PARSED, () => {
        videoEl.value?.play().catch((e) => {
          console.error("自动播放失败:", e);
        });
      });

      hlsInstance.value.on(Hls.Events.ERROR, (event, data) => {
        if (data.fatal) {
          switch (data.type) {
            case Hls.ErrorTypes.NETWORK_ERROR:
              console.error("网络错误，尝试恢复...");
              hlsInstance.value?.startLoad();
              break;
            case Hls.ErrorTypes.MEDIA_ERROR:
              console.error("媒体错误，尝试恢复...");
              hlsInstance.value?.recoverMediaError();
              break;
            default:
              console.error("无法恢复的错误");
              // destroyHlsPlayer();
              break;
          }
        }
      });
    } else if (videoEl.value.canPlayType("application/vnd.apple.mpegurl")) {
      // 原生支持HLS的浏览器（如Safari）
      videoEl.value.src = videoUrl.value;
      videoEl.value.addEventListener("loadedmetadata", () => {
        videoEl.value?.play().catch((e) => {
          console.error("自动播放失败:", e);
        });
      });
    }
  } catch (error) {
    console.error("初始化HLS播放器失败:", error);
  }
};

// // 开始记录播放时长
// const startTracking = () => {
//   // 每10秒记录一次到服务器
//   intervalId.value = setInterval(() => {
//     if (maxPlayedDuration.value > 0) {
//       savePlayProgress(maxPlayedDuration.value);
//     }
//   }, 10000); // 10秒一次
// };

// // 保存播放进度到服务器
// const savePlayProgress = async (duration: number) => {
//   try {
//     // 这里调用API接口
//     formsaveRecord.cTime = duration;
//     await catsaveRecordDetail(formsaveRecord).then((res: any) => {});
//   } catch (error) {
//     // console.error("保存进度失败:", error);
//   }
// };
// 销毁HLS实例
const destroyHlsPlayer = () => {
  if (hlsInstance.value) {
    hlsInstance.value.destroy();
    hlsInstance.value = null;
  }

  // 1. 清除定时器
  // if (intervalId.value) {
  //   clearInterval(intervalId.value);
  //   intervalId.value = null;
  // }
  // 2. 移除video元素的事件监听
  if (videoEl.value) {
    // videoEl.value.removeEventListener("timeupdate", handleTimeUpdate);
    // 重置video元素
    videoEl.value.pause();
    videoEl.value.removeAttribute("src");
    videoEl.value.load();
  }
};
const from = reactive({
  page: "1",
  limit: "10",
  vid: "",
});
const videoList = ref();
const videoname = ref();
const video = () => {
  // if (route.query.id == "1") {
  //   from.vid = receivedData;
  // }

  catstudyCourse(from).then((res: any) => {
    videoList.value = res.videoList;
    // contentList.datalist = res.contentList[0];
    // if (route.query.id == "1") {
    //   contentListdata.value.push(res.videoList);

    // }
    //
    videoUrl.value = videoList.value.ListPath;
    poster.value = videoList.value.CoverPath;
    videoname.value = videoList.value.VideoName;
    VideoTime.value = videoList.value.VideoTime - 1;

    if (videoUrl.value) {
      initHlsPlayer().then(() => {
        // startTracking(); // 初始化后开始跟踪
      });
    }
  });
};
const props = defineProps<{
  monopolize: [];
}>();
const details1 = reactive({
  monopolize: [],
});

const visible = ref(false);

const handleOk = () => {
  visible.value = false;
  destroyHlsPlayer();
  
};
const handleCancel = () => {
  visible.value = false;
  destroyHlsPlayer();
};
const videolistao = (e: any) => {
  visible.value = true;
  from.vid = e;
  video();
};

onMounted(() => {
  if (props.monopolize) {
    details1.monopolize = props.monopolize;
  }
});
onBeforeUnmount(() => {
  destroyHlsPlayer();
  // 最终保存一次进度
  // if (maxPlayedDuration.value > 0) {
  //   savePlayProgress(maxPlayedDuration.value);
  // }
  // if (videosRightRef.value) {
  //   videosRightRef.value.removeEventListener("scroll", handleScroll);
  // }
});
</script>
<style lang="less" scoped>
.details {
  //   width: 15vw;
  margin-top: 2vw;
  font-weight: 500;
  font-size: 17px;
  color: #03305c;
  text-decoration: underline;
  text-decoration-color: #0075ff;
}
.imgliyu {
  width: 20px;
  height: 20px;
  margin-left: 1vw;
  img {
    width: 25px;
    // height: 20px;
  }
}
.details-text {
  margin: 1vw 0;
  font-size: 14px;
  color: #03305c;
}
.table-listname {
  text-align: left;
  margin: 1vw 0;
  font-weight: 700;
  font-size: 1vw;
  color: #03305c;
  background-color: #fff;
  page-break-inside: avoid;
  break-inside: avoid;
}
.tablesname {
  padding: 1vw;
  font-size: 14px;
}
/* 表格样式 */
.course-table {
      overflow: hidden;
      border: 1px solid #e5e7eb;
      border-collapse: collapse;
      text-align: center;
      margin: 0.5vw;
      font-size: 1vw;
      color: #03305c;
    }
.course-table th {
  padding: 0.5vw 0.5vw;
  text-align: center;
  border: 1px solid #e5e7eb;

  font-weight: 500;
}
/* 课程名称列样式 */
.course-name {
  width: 30%; /* 增加课rgb(134, 139, 149)*/
  white-space: normal; /* 允许内容换行 */
  word-wrap: break-word; /* 长单词换行 */
  word-break: break-all; /* 允许在任意字符处换行 */
}

.course-table td {
  padding: 0.5vw 0.5vw;
  text-align: center;
  border-bottom: 1px solid #e5e7eb;
}


.course-table tr:hover {
  background-color: #f9fafb;
  transition: background-color 0.15s ease;
}

.nowrap {
  white-space: nowrap;
}

.truncate {
  max-width: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
@media (max-width: 735px) {
  .course-table {
  padding: 0.5vw 0.5vw;
  text-align: center;
  border: 1px solid #e5e7eb;
  font-size: 3vw;
}
}
</style>
